package fr.ups.jim.isi.tp4;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;

public class PersistentCanvas extends Component {

	private static final long serialVersionUID = 1L;
	ArrayList<CanvasItem> itemsList;
	
    PersistentCanvas() {
    	itemsList = new ArrayList<CanvasItem>();
    }

    /**
     * Add a CanvasItem to the current Persistent Canvas
     * @param item		Given CanvasItem
     * @return			If add a not null CanvasItem, return true, else false
     */
    public boolean addItem(CanvasItem item) {
    	if (item != null) {
    		itemsList.add(item);
    		repaint();
    		return true;
    	}
    	else
    		return false;
    }
    
    /**
     * Remove a CanvasItem from the current Persistent Canvas
     * @param item		Given CanvasItem
     * @return			If successfully delete an item, return true, else false
     */
    public boolean removeItem (CanvasItem item) {
    	if (item != null){
    		itemsList.remove(item);
    		repaint();
    		return true;
    	}
    	else
    		return false;
    }
    
    /**
     * check the given point is within which Canvas Item
     * @param p		given point
     * @return		the CanvasItem contains the given point
     */
    public CanvasItem getItemContainsPoint(Point p) {
    	
    	// attention to the iterating order is a reverse order, because here 
    	// we try to find the Item latest drawn by the user
    	for (int i = itemsList.size() - 1; i >= 0; i--) {
    		if (itemsList.get(i).contains(p)) {
//    			System.out.println(i);
    			return itemsList.get(i);
    		}
    	}
    	
    	return null;
    }
    
    
    /**
     * Paint this persistent canvas
     */
    public void paint(Graphics graphics) {
	   Graphics2D g = (Graphics2D)graphics ;

	   g.setColor(getBackground()) ;
	   g.fillRect(0, 0, getWidth(), getHeight()) ;
	   	   
	   for (CanvasItem item : itemsList) 
		   item.paint(g);
	   
    }
	   
}